package com.sunlee.common.core.entity;

import com.sunlee.common.core.exception.BusinessException;
import com.sunlee.common.core.enums.ErrorCodeEnum;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

/**
 * 响应数据
 *
 * @author sunlee
 */
@ApiModel(value = "响应")
public class Result<T> {
    /**
     * 编码：0表示成功，其他值表示失败
     */
    @ApiModelProperty(value = "编码：0表示成功，其他值表示失败")
    private int code;
    /**
     * 消息内容
     */
    @ApiModelProperty(value = "消息内容")
    private String msg;
    /**
     * 响应数据
     */
    @ApiModelProperty(value = "响应数据")
    private T data;

    private Result() {
    }

    private Result(int code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public static <T> Result<T> ok(T data) {
        return new Result<>(ErrorCodeEnum.SUCCESS.getCode(), ErrorCodeEnum.SUCCESS.getMsg(), data);
    }

    public static <T> Result<T> ok() {
        return new Result<>(ErrorCodeEnum.SUCCESS.getCode(), ErrorCodeEnum.SUCCESS.getMsg(), null);
    }

    public static <T> Result<T> error() {
        return new Result<>(ErrorCodeEnum.SERVER_INTERNAL_ERROR.getCode(), ErrorCodeEnum.SERVER_INTERNAL_ERROR.getMsg(), null);
    }

    public static <T> Result<T> error(int code) {
        return new Result<>(code, ErrorCodeEnum.msgOfCode(code), null);
    }

    public static <T> Result<T> error(int code, String msg) {
        return new Result<>(code, msg, null);
    }

    public static <T> Result<T> error(String msg) {
        return new Result<>(ErrorCodeEnum.SERVER_INTERNAL_ERROR.getCode(), msg, null);
    }

    public static <T> Result<T> error(ErrorCodeEnum errorEnum) {
        return new Result<>(errorEnum.getCode(), errorEnum.getMsg(), null);
    }

    public static <T> Result<T> error(BusinessException ex) {
        return new Result<>(ex.getCode(), ex.getMsg(), null);
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}
